import React from 'react';
import ReactDOM from 'react-dom';
import style from './HYNumberInput.less';
import HYInput from '../HYInput/HYInput';

export interface HYNumberInputProps {
  min?: number;
  max?: number;
  numberValue?: number;
  onChangeNumber: (value: number) => void;
}

/**
 * 左右有加号的数字输入
 */
class HYNumberInput extends React.Component<HYNumberInputProps, any> {
  static defaultProps: {
    min: 0;
    max: 100;
  };
  private input: any;

  constructor(props) {
    super(props);
    this.onChange.bind(this);
  }

  subButton: any;
  addButton: any;
  onChange = (e) => {
    const { value } = e.target;
    const reg = /^-?\d+$/;
    console.log('HYNumberInput.onChange', value);
    if (
      (!isNaN(value) &&
        reg.test(value) &&
        (value >= this.props.min && value <= this.props.max)) ||
      value === '' ||
      value === '-'
    ) {
      this.checkStyle(value);
      // this.setState({ number: parseInt(value) });
      this.props.onChangeNumber(parseInt(value));
    }
  };

  componentDidMount() {
    console.log(
      'HYNumberInput.componentDidMount',
      this.props.numberValue,
      typeof this.props.numberValue
    );
    // @ts-ignore
    let elements = ReactDOM.findDOMNode(this.input).querySelectorAll(
      '.ant-input-group-addon'
    );
    if (elements) {
      this.subButton = elements[0];
      this.addButton = elements[1];
      this.subButton.onclick = () => {
        this.onChange({ target: { value: this.props.numberValue - 1 } });
      };
      this.addButton.onclick = () => {
        this.onChange({ target: { value: this.props.numberValue + 1 } });
      };
      this.subButton.classList.add(style['ant-input-group-addon']);
      this.addButton.classList.add(style['ant-input-group-addon']);
      this.checkStyle(this.props.numberValue);
    }
  }

  render() {
    console.log('HYNumberInput.render', this.props.numberValue);
    return (
      <HYInput
        ref={(input) => (this.input = input)}
        onChange={this.onChange}
        addonBefore={'-'}
        addonAfter={'+'}
        value={this.props.numberValue}
      />
    );
  }

  private checkStyle(value: number) {
    if (value === this.props.min) {
      this.subButton.classList.add(style['ant-input-group-addon-disable']);
    } else {
      this.subButton.classList.remove(style['ant-input-group-addon-disable']);
    }
    if (value === this.props.max) {
      this.addButton.classList.add(style['ant-input-group-addon-disable']);
    } else {
      this.addButton.classList.remove(style['ant-input-group-addon-disable']);
    }
  }
}

export default HYNumberInput;
